#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
using namespace std;

struct ListNode {
    int val;
    struct ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* solve(vector<ListNode*>& a) {
    map<int,int> mp1;
    map<int,int> mp2;
    for(auto t:a){
        for(ListNode *w = t; w->next != nullptr; w = w->next){
            mp1[w->val] = w->next->val;
            mp2[w->next->val] = w->val;
        }
    }

    int cnt = 1;

    int x = mp1.begin()->first;
    // cout << x << endl;

    ListNode* ans = new ListNode(x);

    ListNode* p = ans;

    if(mp1[x] < mp2[x]){
        for(int i=mp1[x]; i!=x; i=mp1[i] ){
            cnt++;
            p->next = new ListNode(i);
            p = p->next;
        }
    }else {
        for(int i=mp2[x]; i!=x; i=mp2[i]){
            cnt++;
            p->next = new ListNode(i);
            p = p->next;
        }
    }
    return ans;
}

int main() {
    vector<ListNode*> a;
    ListNode* p;

    p = new ListNode(1);
    p->next = new ListNode(2);p = p->next;
    p->next = new ListNode(3);p = p->next;
    a.push_back(p);

    p = new ListNode(2);

    p->next = new ListNode(3);p = p->next;
    p->next = new ListNode(4);p = p->next;

    a.push_back(p);
    p = new ListNode(4);

    p->next = new ListNode(1);p=p->next;
    a.push_back(p);

    ListNode* ans = solve(a);


    while(ans){
        cout << ans->val << " ";
        ans = ans->next;
    }
    return 0;
}